package com.dzl.moive.service.impl;

import com.dzl.asynthread.SyncInitDataServiceImpl;
import com.dzl.constant.CommonConstants;
import com.dzl.moive.dao.WelfareMovieCinemaMapper;
import com.dzl.moive.pojo.WelfareMovieCinema;
import com.dzl.moive.pojo.WelfareMovieCity;
import com.dzl.moive.pojo.WelfareMovieInfo;
import com.dzl.moive.pojo.WelfareMoviePremiumPriceCache;
import com.dzl.moive.pojo.query.WelfareMovieCinemaQuery;
import com.dzl.moive.pojo.query.WelfareMovieCinemaWithCodeQuery;
import com.dzl.moive.pojo.vo.WelfareMovieCinemaVo;
import com.dzl.moive.pojo.vo.WelfareMovieDateVo;
import com.dzl.moive.pojo.vo.WelfareMovieOpiDetailVo;
import com.dzl.moive.pojo.vo.WelfareMovieTicketVo;
import com.dzl.moive.service.WelfareMovieCinemaService;
import com.dzl.moive.service.WelfareMovieCityService;
import com.dzl.moive.service.WelfareMovieInfoService;
import com.dzl.moive.service.WelfareMoviePremiumPriceCacheService;
import com.dzl.moive.utils.MovieUtils;
import com.dzl.util.DateUtil;
import com.dzl.util.DoubleUtil;
import com.dzl.util.EmptyUtils;
import com.dzl.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电影院(welfare_movie_cinema)表服务实现类
 * @author liuguanjun
 * @since 2021-11-02 11:14:42
 */
@Slf4j
@Service("welfareMovieCinemaService")
public class WelfareMovieCinemaServiceImpl implements WelfareMovieCinemaService {

    @Autowired
    private WelfareMovieCinemaMapper mapper;
    @Autowired
    private WelfareMovieCityService welfareMoiveCityService;
    @Autowired
    private SyncInitDataServiceImpl syncInitDataServiceImpl;
    @Autowired
    private WelfareMovieInfoService welfareMoiveInfoService;
    @Autowired
    private WelfareMoviePremiumPriceCacheService welfareMoviePremiumPriceCacheService;

    @Override
    public PageInfo<WelfareMovieCinemaVo> getWelfareMovieCinemaVoListPage(WelfareMovieCinemaQuery query) {
        PageHelper.startPage(query);
        List<WelfareMovieCinemaVo> list = mapper.selectWelfareMovieCinemaVoList(query);
        if(EmptyUtils.isNotEmpty(list)){
            for (WelfareMovieCinemaVo cinema:list) {
                Double juli = Double.valueOf(cinema.getDistance());
                if(juli>1){
                    cinema.setDistance(DoubleUtil.round(juli,2)+"千米");
                }else{
                    cinema.setDistance(Math.round(juli*1000)+"米");
                }
            }
        }
        PageInfo<WelfareMovieCinemaVo> page = new PageInfo<WelfareMovieCinemaVo>(list);
        return page;
    }

    @Override
    public List<WelfareMovieCinemaVo> getWelfareMoviePlayCinemaVoList(WelfareMovieCinemaQuery query) {
        String cinemaids = MovieUtils.getMoviePlayCinemaList(query.getMovieid(),query.getCitycode(),query.getPlaydate());
        if(EmptyUtils.isEmpty(cinemaids)){
            return new ArrayList<>();
        }
        query.setCinemaids(cinemaids);
        List<WelfareMovieCinemaVo> list = mapper.selectWelfareMovieCinemaVoList(query);
        if(EmptyUtils.isNotEmpty(list)){
            for (WelfareMovieCinemaVo cinema:list) {
                Double juli = Double.valueOf(cinema.getDistance());
                if(juli>1){
                    cinema.setDistance(DoubleUtil.round(juli,2)+"千米");
                }else{
                    cinema.setDistance(Math.round(juli*1000)+"米");
                }
            }
        }
        return list;
    }

    /*******
     * 获取今天及后面7天的日期
     * @return
     */
    public List<WelfareMovieDateVo> getMovieDateList(String curryDay,String startDay) {
        List<WelfareMovieDateVo> list = new ArrayList<>();
        long quot = DateUtil.getQuot(DateUtil.getToday(),startDay);
        for(int i=0;i<8;i++){
            WelfareMovieDateVo welfareMovieDateVo = new WelfareMovieDateVo();
            Date date  = DateUtil.getOffsetDate(i+ Integer.valueOf(quot+""));
            String fullDayName = DateUtil.format2Date(date);
            welfareMovieDateVo.setDayFullName(fullDayName);
            welfareMovieDateVo.setDayName(fullDayName.split("-")[1]+"-"+fullDayName.split("-")[2]);
            long quot_ = DateUtil.getQuot(DateUtil.getToday(),fullDayName);
            if(quot_==0){
                welfareMovieDateVo.setDay("今天");
            }else if(quot_==1){
                welfareMovieDateVo.setDay("明天");
            }else{
                welfareMovieDateVo.setDay(DateUtil.getWeekOfDate(date));
            }
            if(fullDayName.equals(curryDay)){
                welfareMovieDateVo.setIsChecked(CommonConstants.YES);
            }
            list.add(welfareMovieDateVo);
        }
        return list;
    }

    @Override
    public WelfareMovieCinema getMovieCinemaInfo(Integer cinemaid) {
        return mapper.selectByPrimaryKey(cinemaid);
    }

    @Override
    public WelfareMovieCinemaVo getMovieCinemaDetail(Integer cinemaid, Integer movieid, String playdate) {
        WelfareMovieCinemaVo welfareMovieCinemaVo = new WelfareMovieCinemaVo();
        WelfareMovieCinema welfareMovieCinema = MovieUtils.getCinemaDetail(cinemaid);
        List<WelfareMovieOpiDetailVo> opiVoList = MovieUtils.getMovieOpiList(cinemaid);
        BeanUtils.copyProperties(welfareMovieCinema,welfareMovieCinemaVo);
        //获取开始时间
        String startDay = DateUtil.getToday();
        //获取选择时间，若未选择时间，则默认取当天
        if(EmptyUtils.isEmpty(playdate)){
            playdate = DateUtil.getToday();
        }
        if(EmptyUtils.isNotEmpty(movieid)){
            WelfareMovieInfo welfareMovieInfo = welfareMoiveInfoService.getMovieInfo(movieid);
            //预售,则根据预售日期查
            if(welfareMovieInfo.getCanbuy().equals("true") && EmptyUtils.isNotEmpty(welfareMovieInfo.getBuytype()) && welfareMovieInfo.getBuytype().equals("prebuy")){
                if(playdate.equals(DateUtil.getToday())){
                    playdate = welfareMovieInfo.getPlaydate();
                }
                startDay = welfareMovieInfo.getPlaydate();
            }
        }
        if(EmptyUtils.isNotEmpty(opiVoList)){
            List<WelfareMovieOpiDetailVo> movielist = new ArrayList<>();
            List<WelfareMovieOpiDetailVo> opiliist = new ArrayList<>();
            Set<String> movieIdSet = new HashSet<>();
            Integer checkMovieId = 0;
            for (int i=0 ; i<opiVoList.size(); i++) {
                WelfareMovieOpiDetailVo opi  = opiVoList.get(i);
                //过滤排片数据取当前选择日期的排片
                if(!movieIdSet.contains(opi.getMovieid()) && opi.getPlaytime().contains(playdate)){
                    //设置选中的排片
                    if(EmptyUtils.isNotEmpty(movieid) && movieid.equals(Integer.valueOf(opi.getMovieid()))){
                        opi.setIsChecked(CommonConstants.YES);
                        checkMovieId = movieid;
                    }
                    //计算电影时长
                    opi.setDuration(DateUtil.getIntervalMillis(opi.getClosetime(),opi.getPlaytime())/1000/60+"分钟");
                    movieIdSet.add(opi.getMovieid());
                    WelfareMovieInfo welfareMovieInfo = welfareMoiveInfoService.getMovieInfo(Integer.valueOf(opi.getMovieid()));
                    if(EmptyUtils.isNotEmpty(welfareMovieInfo)){
                        opi.setMovielogo(welfareMovieInfo.getLogo());
                    }
                    opi.setOriginalPrice(opi.getPrice());
                    movielist.add(opi);
                }
            }
            if(movieIdSet.size()>0){
                if(checkMovieId == 0){
                    checkMovieId = Integer.valueOf(movielist.get(0).getMovieid());
                    movielist.get(0).setIsChecked(CommonConstants.YES);
                }
                //查询电影详情，获取溢价值
                WelfareMovieInfo welfareMovieInfo = welfareMoiveInfoService.getMovieInfo(checkMovieId);
                for (int i=0 ; i<opiVoList.size(); i++) {
                    WelfareMovieOpiDetailVo opi  = opiVoList.get(i);
                    if(opi.getMovieid().equals(checkMovieId.toString()) && opi.getPlaytime().contains(playdate)){
                        //放映时间和结束时间转换为HH:mm格式
                        String closeTime = opi.getClosetime().split(" ")[1];
                        String playTime = opi.getPlaytime().split(" ")[1];
                        opi.setClosetime(closeTime.substring(0,closeTime.length()-3));
                        opi.setPlaytime(playTime.substring(0,playTime.length()-3));
                        //电影价格有分转为元
                        BigDecimal price = new BigDecimal(opi.getPrice()).divide(new BigDecimal(100));
                        //电影价格加上溢价
                        if(EmptyUtils.isNotEmpty(welfareMovieInfo)){
                            price = price.add(welfareMovieInfo.getPremiumPrice());
                        }else{
                            //查询系统设置溢价
                            WelfareMoviePremiumPriceCache welfareMoviePremiumPriceCache =  welfareMoviePremiumPriceCacheService.selectByPrimaryKey(1);
                            if(EmptyUtils.isNotEmpty(welfareMoviePremiumPriceCache)){
                                price = price.add(welfareMoviePremiumPriceCache.getPremiumPrice());
                            }else{
                                price = price.add(WelfareMovieInfo.premiumPriceDefault);
                            }
                        }
                        opi.setPrice(price.setScale(1,BigDecimal.ROUND_HALF_UP).toString());
                        opiliist.add(opi);
                    }
                }
            }
            if(EmptyUtils.isNotEmpty(opiliist)){//根据放映时间进行排序
                opiliist = opiliist.stream().sorted(Comparator.comparing(WelfareMovieOpiDetailVo::getPlaytime)).collect(Collectors.toList());
            }
            welfareMovieCinemaVo.setMovielist(movielist);
            if(EmptyUtils.isNotEmpty(movielist)){
                //同步更新电影上映影院关联数据
                boolean lock = RedisUtil.tryLock("ADD_MOVIE_CINEMA_REL:" , 1000*10);
                if(lock){
                    syncInitDataServiceImpl.addMovieCanemaRel(cinemaid,movielist);
                }
            }
            welfareMovieCinemaVo.setOpiliist(opiliist);
        }
        //获取日期
        List<WelfareMovieDateVo> dateList = getMovieDateList(playdate,startDay);
        welfareMovieCinemaVo.setDateList(dateList);
        return welfareMovieCinemaVo;
    }

    @Override
    public WelfareMovieTicketVo getWelfareMovieTicket(String opiid) {
        WelfareMovieTicketVo welfareMovieOpiSeatVo = MovieUtils.getOpiSeat(opiid);
        WelfareMovieOpiDetailVo welfareMovieOpiDetailVo = MovieUtils.getOpiDetail(opiid);
        if(EmptyUtils.isNotEmpty(welfareMovieOpiDetailVo) && EmptyUtils.isNotEmpty(welfareMovieOpiSeatVo)){
            BeanUtils.copyProperties(welfareMovieOpiDetailVo,welfareMovieOpiSeatVo);
            String playTime = welfareMovieOpiSeatVo.getPlaytime();
            String playTimeYear = playTime.split(" ")[0];
            String playTimeHours = playTime.split(" ")[1];
            String closeTime = welfareMovieOpiSeatVo.getClosetime();
            String closeTimeHours = closeTime.split(" ")[1];
            StringBuilder playTimeStr = new StringBuilder();
            String fullDayName = DateUtil.format2Date(DateUtil.parseDate(playTime));
            long quot_ = DateUtil.getQuot(DateUtil.getToday(),fullDayName);
            if(quot_==0){
                playTimeStr.append("今天 ");
            }else if(quot_==1){
                playTimeStr.append("明天 ");
            }else{
                String date  = DateUtil.getWeekOfDate(DateUtil.parseDate(playTime));
                playTimeStr.append(date+" ");
            }
            playTimeStr.append((playTimeYear.split("-")[1]+"-"+playTimeYear.split("-")[2]).replace("-","月")+"日 ");
            playTimeStr.append(playTimeHours.substring(0,playTimeHours.length()-3)+"-"+closeTimeHours.substring(0,closeTimeHours.length()-3));
            welfareMovieOpiSeatVo.setPlaytime(playTimeStr.toString());
            BigDecimal costPrice = new BigDecimal(welfareMovieOpiDetailVo.getPrice()).divide(new BigDecimal(100));
            welfareMovieOpiSeatVo.setCostPrice(costPrice.setScale(1,BigDecimal.ROUND_HALF_UP).toString());
            //查询电影详情，获取溢价值
            WelfareMovieInfo welfareMovieInfo = welfareMoiveInfoService.getMovieInfo(Integer.valueOf(welfareMovieOpiSeatVo.getMovieid()));
            //电影价格有分转为元
            BigDecimal price = new BigDecimal(welfareMovieOpiSeatVo.getPrice()).divide(new BigDecimal(100));
            //电影价格加上溢价
            if(EmptyUtils.isNotEmpty(welfareMovieInfo)){
                price = price.add(welfareMovieInfo.getPremiumPrice());
            }else{
                //查询系统设置溢价
                WelfareMoviePremiumPriceCache welfareMoviePremiumPriceCache =  welfareMoviePremiumPriceCacheService.selectByPrimaryKey(1);
                if(EmptyUtils.isNotEmpty(welfareMoviePremiumPriceCache)){
                    price = price.add(welfareMoviePremiumPriceCache.getPremiumPrice());
                }else{
                    price = price.add(WelfareMovieInfo.premiumPriceDefault);
                }
            }
            welfareMovieOpiSeatVo.setPrice(price.setScale(1,BigDecimal.ROUND_HALF_UP).toString());
        }
        return welfareMovieOpiSeatVo;
    }


    @Override
    public Integer snycMovieCinema(Integer pageNo) {
        //查询所有城市信息
        List<WelfareMovieCity> citylist = welfareMoiveCityService.getCityList("",CommonConstants.NO);
        if(EmptyUtils.isNotEmpty(citylist)){
            Integer pageSize = 20;
            for (WelfareMovieCity city:citylist) {
                String citycode = city.getCitycode();
                syncInitDataServiceImpl.addMovieCinema(citycode,pageNo,pageSize,city.getId());
            }
            return citylist.size();
        }
        return 0;
    }

    @Override
    public PageInfo<WelfareMovieCinema> getMovieCinemaListPage(WelfareMovieCinemaWithCodeQuery query) {
        PageHelper.startPage(query);
        List<WelfareMovieCinema> list = mapper.getMovieCinemaListPage(query);
        PageInfo<WelfareMovieCinema> page = new PageInfo<WelfareMovieCinema>(list);
        return page;
    }
}